<template>
  <!-- 添加/编辑 -->
  <el-dialog center
             width="35%"
             :show-close="false"
             :close-on-click-modal="false"
             :close-on-press-escape="false"
             :title="!dataForm.id ? '新增' : '编辑'"
             :visible.sync="visible"
             @opened="handleOpenedDialog"
             @closed="handleClosedDialog">
    <!-- Dialog 内容主体区域 -->
    <el-form size="small"
             label-width="60px"
             ref="dataForm"
             :model="dataForm"
             :rules="dataRule"
             @keyup.enter.native="dataFormSubmit">
      <el-form-item prop="name"
                    label="姓名">
        <el-input clearable
                  show-word-limit
                  ref="nameRef"
                  style="width:50%"
                  maxlength="30"
                  placeholder="输入姓名"
                  prefix-icon="el-icon-edit"
                  v-model.trim="dataForm.name"></el-input>
      </el-form-item>
      <el-form-item prop="age"
                    label="年龄">
        <el-input-number clearable
                         placeholder="输入年龄"
                         style="width:50%"
                         :min="0"
                         :max="99"
                         :precision="0"
                         @mousewheel.native.prevent
                         @mousewheel.native="mouseWheelChange('age',1)"
                         v-model="dataForm.age"></el-input-number>
      </el-form-item>
      <el-form-item prop="sex"
                    label="性别">
        <el-select style="width:50%"
                   v-model="dataForm.sex">
          <el-option v-for="item in 2"
                     :key="item-1"
                     :label="`${item-1 ? '男' : '女'}`"
                     :value="item-1">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item prop="email"
                    label="邮箱">
        <el-input clearable
                  show-word-limit
                  maxlength="50"
                  placeholder="邮箱"
                  prefix-icon="el-icon-message"
                  v-model.trim="dataForm.email"></el-input>
      </el-form-item>
      <el-form-item>
        <el-switch v-if="dataForm.id"
                   v-model="version"
                   inactive-text="更新方式(主键)"
                   active-text="更新方式(主键+乐观锁)"></el-switch>
      </el-form-item>
    </el-form>

    <!-- Dialog 底部区域 -->
    <span slot="footer"
          class="dialog-footer">
      <el-button size="small"
                 @click="onClosedDialog">取 消</el-button>
      <el-button size="small"
                 type="primary"
                 @click="dataFormSubmit">{{!dataForm.id ? '保 存' : '更 新'}}</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { copyProperties } from '@/utils'
import { selectById, insert, update } from '@/api/busiDemo/jbdpDemoCrud'
export default {
  name: 'jbdpDemoCrudAddOrUpdate',
  data() {
    return {
      visible: false,
      dataForm: {
        id: 0,
        name: '',
        age: 0,
        sex: 1,
        email: '',
        version: 0
      },
      dataRule: {
        name: [{
          trigger: 'blur', required: true, message: '姓名不能为空'
        }],
        email: [{
          trigger: 'blur', pattern: /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/, message: '邮箱格式不正确'
        }]
      },
      version: false
    }
  },
  methods: {
    handleOpenedDialog() {
      this.$nextTick(() => {
        this.$refs.nameRef.focus()
      })
    },
    handleClosedDialog() {
      // Dialog 关闭时，重置表单并移除校验结果
      this.$refs.dataForm.resetFields()
      // 解决(编辑->新建)时数据回显问题
      this.dataForm = {
        id: 0,
        name: '',
        age: 0,
        sex: 1,
        email: '',
        version: 0
      }
    },
    onClosedDialog() {
      this.visible = false
    },
    // 控制滚轮改变数值
    mouseWheelChange(name, step) {
      // console.log('event', step);
      event.wheelDelta > 0 ? this.dataForm[name] += step : this.dataForm[name] -= step
    },
    // 页面初始化
    async init(id) {
      this.dataForm.id = typeof id === 'number' ? id : 0
      if (this.dataForm.id) {
        // 查询请求
        const res = await selectById(this.dataForm.id)
        console.log('init', res)
        if (res.data.success) {
          copyProperties(this.dataForm, res.data.data)
        }
      }
      this.visible = true
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs.dataForm.validate(async valid => {
        // false 校验未通过
        if (!valid) { return }
        let res
        try {
          if (this.dataForm.id) {
            let id = this.dataForm.id
            let args = this.dataForm
            if (this.version) {
              // 更新方式(主键+乐观锁)
              args = {
                condition: [{
                  property: 'id',
                  value: id,
                  type: 'EQ'
                }, {
                  property: 'version',
                  value: args.version,
                  type: 'EQ'
                }],
                value: args
              }
              id = ''
            }
            // console.log('update', id, JSON.stringify(args))
            // 更新
            res = await update(id, args)
          } else {
            // 新增时不需要携带主键、乐观锁标识
            delete this.dataForm.id
            delete this.dataForm.version
            res = await insert(this.dataForm)
          }
          console.log('dataFormSubmit', res)
          if (!res.data.success) {
            return this.$message.error(res.data.message)
          }
          this.$message.success(!this.dataForm.id ? '保存成功' : '更新成功')
          this.visible = false
          // this.$emit 子组件向外触发事件(调用父组件的 refreshDataList 自定义方法)
          this.$emit('refreshDataList')
        } catch (e) {
          // console.log('dataFormSubmit error', e.response.data.message)
          this.$message.error(e.response.data.message)
        }
      })
    }
  }
}
</script>

<style scoped>
</style>
